"""
脚本模型定义
包含脚本文件夹和用户脚本相关模型
"""
from datetime import datetime
from . import db
from ..timezone_utils import now as timezone_now

class ScriptFolder(db.Model):
    """脚本文件夹模型"""
    __tablename__ = 'script_folders'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text)
    parent_id = db.Column(db.Integer, db.ForeignKey('script_folders.id'), index=True)  # 父文件夹ID
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    created_at = db.Column(db.DateTime, default=timezone_now, nullable=False)
    updated_at = db.Column(db.DateTime, default=timezone_now, onupdate=timezone_now, nullable=False)
    
    # 关系
    user = db.relationship('User', backref='script_folders')
    parent = db.relationship('ScriptFolder', remote_side=[id], backref='subfolders')
    scripts = db.relationship('UserScript', backref='folder', lazy='dynamic', cascade='all, delete-orphan')
    
    def to_dict(self, include_children=False):
        """转换为字典"""
        result = {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'parent_id': self.parent_id,
            'user_id': self.user_id,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }
        
        if include_children:
            result['subfolders'] = [subfolder.to_dict() for subfolder in self.subfolders]
            result['scripts'] = [script.to_dict() for script in self.scripts]
            
        return result
    
    def __repr__(self):
        return f'<ScriptFolder {self.name}>'


class UserScript(db.Model):
    """用户脚本模型"""
    __tablename__ = 'user_scripts'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text)
    folder_id = db.Column(db.Integer, db.ForeignKey('script_folders.id'), index=True)  # 所属文件夹
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, index=True)
    language = db.Column(db.String(50), nullable=False, default='python')  # 脚本语言
    is_active = db.Column(db.Boolean, nullable=False, default=True)  # 是否激活
    tags = db.Column(db.Text)  # 标签，JSON格式
    created_at = db.Column(db.DateTime, default=timezone_now, nullable=False)
    updated_at = db.Column(db.DateTime, default=timezone_now, onupdate=timezone_now, nullable=False)
    
    # 关系
    user = db.relationship('User', backref='user_scripts')
    
    # 注意：脚本内容不再存储在数据库中，而是存储在文件系统中
    # 使用 services.shared.file_utils 中的函数来读取和保存脚本内容
    
    def to_dict(self):
        """转换为字典"""
        # 构建完整路径
        full_path = self.name
        if self.folder:
            try:
                from services.shared.folder_utils import get_folder_full_path
                folder_path = get_folder_full_path(self.folder, self.user_id, self.user.username)
                full_path = f"{folder_path}/{self.name}"
            except Exception:
                # 如果获取路径失败，使用文件夹名称
                full_path = f"{self.folder.name}/{self.name}" if self.folder else self.name
        
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'folder_id': self.folder_id,
            'folder_name': self.folder.name if self.folder else None,
            'full_path': full_path,
            'user_id': self.user_id,
            'language': self.language,
            'is_active': self.is_active,
            'tags': self.tags,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }
    
    def __repr__(self):
        return f'<UserScript {self.name}>'